//uses WebAudio

var doll = (function (_doll) {
    _doll.audio = _doll.audio || {};

    _doll.audio.init = function() {
        console.log('*Audio Initialization*');
        _doll.audio.src = [];
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            _doll.audio.context = new AudioContext();
        }
        catch(e) {
            _doll.audio.not_supported(e)
        }
    };

    _doll.audio.create_source = function(i) {
        return function(data) {
            console.log('audio: creating source');
            _doll.audio.context.decodeAudioData(data, function(buffer) {
                _doll.audio.src[i] = _doll.audio.context.createBufferSource();
                _doll.audio.src[i].buffer = buffer;
                _doll.audio.loaded++;
                if(_doll.audio.loaded == _doll.audio.numfiles) {
                    _doll.audio.complete();
                }
            });
        }
    };

    _doll.audio.play = function(num) {
        _doll.audio.src[num].connect(_doll.audio.context.destination);
        _doll.audio.src[num].start(0);
    };

    //returns the offset for the first sound provided
    //so use fetch(mysounds); play(0+offset); for first sound in
    //mysounds array even if other songs were already loaded
    _doll.audio.fetch = function(files, use_load_screen) {
        var offset = _doll.audio.src.length;
        console.log('fetch audio..');
        _doll.audio.loaded = 0;
        _doll.audio.numfiles = files.length;
        if(_doll.audio.numfiles == 0) {
            _doll.audio.complete();
            return;
        }
        //fetches audio files sends data to callback
        for(var i=0; i<files.length; i++) {
            _doll.fetch.sound(files[i], _doll.audio.create_source(i), use_load_screen);
        }
        return offset;
    };

    //called when all audio files are loaded...
    _doll.audio.complete = function() { 
        console.log('all audio loaded successfully..'); 
    };

    _doll.audio.error = function(msg) {
        console.log(msg);
    };
    
    _doll.audio.not_supported = function(e) {
        console.log("web audio not supported by user's browser..");
    };

    return _doll;
}(doll || {}));

